﻿using Anonym.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Anonym.Data.Entities;
using System.IO;
using System.Text;

namespace Anonym.Middleware
{
    public class InterfaceLogMiddleware
    {
        private readonly RequestDelegate _next;
        private SqlSugarClient Db { get; set; }

        public InterfaceLogMiddleware(RequestDelegate next, IServiceProvider p)
        {
            Db = p.GetService<DbProvider>().GetInstance();
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            //if (context.Request.Method.ToLower() != "post")
            //{
            //    await _next(context);
            //    return;
            //}


            var originalResponseStream = context.Response.Body;

            HostString sh = context.Request.Host;
            Console.WriteLine($"★Path: {context.Request.Path}");
            Console.WriteLine($"★HasFormContentType: {context.Request.HasFormContentType}");
            Console.WriteLine($"★Query.Count: {context.Request.Query.Count}");
            var tt = context.Request.Scheme;
            //string tt1 = context.Request.Form["aaa"] + "";

            #region Request取值

            context.Request.EnableBuffering();

            string bodyVal = "";
            Stream stream = context.Request.Body;
            var requestReader = new StreamReader(stream);
            ////context.Request.Body.Position = 0;
            bodyVal = await requestReader.ReadToEndAsync();
            context.Request.Body.Position = 0;
            Console.WriteLine($"★RequestBody: {bodyVal}");
            Console.WriteLine($"★--------------------------------------------------------------------");

            await _next(context);

            //using (var ms = new MemoryStream())
            //{
            //    context.Response.Body = ms;
            //    await _next(context);


            //    ms.Position = 0;
            //    var responseReader = new StreamReader(ms);

            //    var responseContent = responseReader.ReadToEnd();
            //    Console.WriteLine($"Response Body: {responseContent}");

            //    ms.Position = 0;

            //    await ms.CopyToAsync(originalResponseStream);
            //    context.Response.Body = originalResponseStream;
            //}






            //// 保持原来的流
            //var originalBody = context.Response.Body;
            //// 用ms替换当前的流
            //var ms = new MemoryStream();
            //context.Response.Body = ms;
            //await _next(context);
            //// 替换其中的内容
            //ms.Seek(0, SeekOrigin.Begin);
            //var reader = new StreamReader(ms);
            //var str = reader.ReadToEnd();
            //var doubleStr = str + str;
            //Console.WriteLine($"RequestBody: {str}");
            ////var buffer = Encoding.UTF8.GetBytes(str);
            ////var ms2 = new MemoryStream();
            ////ms2.Write(buffer, 0, buffer.Length);
            ////ms2.Seek(0, SeekOrigin.Begin);
            ////// 写入到原有的流中
            ////await ms2.CopyToAsync(originalBody);




            //获取到Response.body内容
            //using (var ms = new MemoryStream())
            //{
            //    var orgBodyStream = context.Response.Body;
            //    context.Response.Body = ms;
            //    //context.Response.ContentType = "multipart/form-data";
            //    //执行controller中正常逻辑代码
            //    await _next(context);

            //    using (var sr = new StreamReader(ms))
            //    {
            //        ms.Seek(0, SeekOrigin.Begin);
            //        //得到Action的返回值
            //        var responseJsonResult = sr.ReadToEnd();
            //        Console.WriteLine($"ResponseBody: {responseJsonResult}");
            //        ms.Seek(0, SeekOrigin.Begin);
            //        //如下代码若不注释则会显示Action的返回值 这里做了注释 则清空Action传过来的值  
            //        await ms.CopyToAsync(orgBodyStream);

            //        //responseJsonResult = Regex.Replace(responseJsonResult, "(\":)([0-9]{16,})(,)", "$1\"$2\"$3");
            //        //var alterResult = responseJsonResult;

            //        context.Response.Body = orgBodyStream;
            //        ////显示修改后的数据 
            //        ////await context.Response.WriteAsync(alterResult, Encoding.UTF8);
            //    }
            //}




            //using (var ms = new MemoryStream())
            //{
            //    context.Response.Body = ms;
            //    await _next(context);
            //    ms.Position = 0;
            //    var responseReader = new StreamReader(ms);
            //    var responseContent = await responseReader.ReadToEndAsync();
            //    Console.WriteLine($"Response Body: {responseContent}");
            //    ms.Position = 0;
            //}



            //string repVal = "";
            //var repBody = context.Response.Body;
            //using (var ms = new MemoryStream())
            //{
            //    context.Response.Body = ms;
            //    await _next(context);
            //    //ms.Seek(0, SeekOrigin.Begin);
            //    ms.Position = 0;
            //    var reader = new StreamReader(ms);
            //    repVal = await reader.ReadToEndAsync();
            //    Console.WriteLine($"ResponseBody: {repVal}");
            //    ms.Position = 0;
            //    //ms.Seek(0, SeekOrigin.Begin);
            //    await ms.CopyToAsync(repBody);
            //    context.Response.Body = repBody;
            //}




            //using (var ms = new MemoryStream())
            //{
            //    context.Response.Body = ms;
            //    //await _next(context);


            //    ms.Position = 0;
            //    var responseReader = new StreamReader(ms);

            //    var responseContent = responseReader.ReadToEnd();
            //    Console.WriteLine($"Response Body: {responseContent}");

            //    ms.Position = 0;
            //}







            // Leave the body open so the next middleware can read it.
            //using (var reader = new StreamReader(
            //    context.Request.Body,
            //    encoding: Encoding.UTF8,
            //    detectEncodingFromByteOrderMarks: false,
            //    bufferSize: 1024,
            //    leaveOpen: true))
            //{
            //    var body = await reader.ReadToEndAsync();
            //    // Do some processing with body…

            //    // Reset the request body stream position so the next middleware can read it
            //    context.Request.Body.Position = 0;
            //}



            //Stream stream = context.Request.Body;
            //byte[] buffer = new byte[context.Request.ContentLength.Value];
            //stream.Position = 0L;
            //await stream.ReadAsync(buffer, 0, buffer.Length);
            //string content = Encoding.UTF8.GetString(buffer);


            //context.Request.EnableBuffering();
            //var requestReader = new StreamReader(context.Request.Body);
            ////context.Request.Body.Position = 0;
            //var requestContent = await requestReader.ReadToEndAsync();
            //Console.WriteLine($"Request Body: {requestContent}");
            //context.Request.Body.Position = 0;
            //await _next(context);

            //using (var ms = new MemoryStream())
            //{
            //    context.Response.Body = ms;
            //    await _next(context);


            //    ms.Position = 0;
            //    var responseReader = new StreamReader(ms);

            //    var responseContent = responseReader.ReadToEnd();
            //    Console.WriteLine($"Response Body: {responseContent}");

            //    ms.Position = 0;
            //}

            #endregion

            //var cultureQuery = context.Request.Query["culture"];
            var obj = new Log_Interface();

            obj.Link = context.Request.Path;
            obj.ControlName = "";
            obj.ActionName = "";
            obj.StartTime = DateTime.Now;
            obj.Source = "pc";
            obj.Ver = "1.0";
            obj.UserId = 0; ;
            //obj.ClientTime { get; set; } = new DateTime(1900, 1, 1);
            //public string Par { get; set; } = string.Empty;
            //public string RequestIp { get; set; } = string.Empty;




            //Console.WriteLine("扩展方法中间件开始： | " + DateTime.Now);
            //if (!string.IsNullOrWhiteSpace(cultureQuery))
            //{
            //    var culture = new CultureInfo(cultureQuery);

            //    CultureInfo.CurrentCulture = culture;
            //    CultureInfo.CurrentUICulture = culture;

            //}

            // Call the next delegate/middleware in the pipeline
            //await _next(context);
            //string val = "";
            //var oldRS = context.Response.Body;
            //using (var ms = new MemoryStream())
            //{
            //    context.Response.Body = ms;
            //    ms.Position = 0;
            //    var reader = new StreamReader(ms);
            //    val = reader.ReadToEnd();
            //    ms.Position = 0;
            //    ms.CopyToAsync(oldRS);
            //    context.Response.Body = oldRS;
            //}
            //obj.EndTime = DateTime.Now;
            //obj.WastageTime = (obj.EndTime - obj.StartTime).Seconds;
            //obj.ReturnValue = val;
            //Db.Insertable(obj).ExecuteCommand();
            //Console.WriteLine("扩展方法中间件结束：" + cultureQuery + "|" + DateTime.Now);
        }
    }
    public static class InterfaceLogMiddlewareExtensions
    {
        public static IApplicationBuilder UseInterfaceLog(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<InterfaceLogMiddleware>();
        }
    }
}
